/*
 * Analyze.cpp
 *
 *  Created on: Oct 4, 2010
 *      Author: gibson
 */

#include "Analyze.h"
#include "DataReader.h"
#include "TH2D.h"
#include "TH1I.h"
#include "TCanvas.h"
#include <iostream>
#include "TPad.h"
#include "TApplication.h"
#include "globals.hh"
#include "TFile.h"

using namespace std;

void TCanvas::Closed()
{
        Emit("Closed()");

        gApplication->Terminate(0);
}

Analyze::Analyze(char* path)
{
	CrystalDistribution(path);
}

Analyze::~Analyze()
{
	;
}

void Analyze::CrystalDistribution(char* path)
{
	dataHisto = new TH2D("dataHisto","dataHisto",72,-0.9,0.9,72,-0.9,0.9);
	analyzeHisto = new TH1I("Legend","Crystals hit per Klong event",3000,0,3000);
	dataReader = new DataReader(path);
	proceed = dataReader->ReadNext(dataHisto);

	while(proceed)
	{
		int count = 0;

		for(int i=0 ; i<72 ; i++)
		{
			for(int j=0 ; j<72 ; j++)
			{
				if(i>11 && j>11 && i<60 && j<60)
				{
					if(dataHisto->GetBinContent(i+1,j+1)>MeV)
					{
						count++;
					}
				}
				else
				{
					if((i+1)%2!=0 && (j+1)%2!=0)
					{
						int total = dataHisto->GetBinContent(i+1,j+1);
						total += dataHisto->GetBinContent(i+2,j+1);
						total += dataHisto->GetBinContent(i+1,j+2);
						total += dataHisto->GetBinContent(i+2,j+2);

						if(total>MeV)
						{
							count++;
						}
					}
				}
			}
		}

		analyzeHisto->Fill(count);
		delete dataHisto;
		dataHisto = new TH2D("dataHisto","dataHisto",72,-0.9,0.9,72,-0.9,0.9);
		proceed = dataReader->ReadNext(dataHisto);
	}

	delete dataHisto;
	delete dataReader;

	TCanvas* canvas = new TCanvas("canvas","Number of Crystals Hit per Klong Event",500,400);
	analyzeHisto->Draw();

	TFile* file = new TFile("./output.root","update");
	analyzeHisto->Write();
	file->Close();

	gApplication->Run(true);

	delete analyzeHisto;
}
